/*
 * Buffer.h
 *
 *  Created on: Mar 16, 2013
 *      Author: root
 */

#ifndef BUFFER_H_
#define BUFFER_H_

#include <iostream>
#include <sstream>
#include "rs232.h"
class Buffer{
private:
	unsigned char dataInput;
	std::string dataOutput;
	bool debug;

	void SendStuff(std::string  data){
			for(unsigned int x=0;x<data.size();x++)
				RS232_SendByte(24,data[x]);
		}
	void resetInput(){dataInput = ' ';}
public:
	Buffer(){
		debug = false;
		RS232_OpenComport(24,9600);
		dataInput = (unsigned char)' ';
		sleep(5);
	}
	~Buffer(){
		RS232_CloseComport(24);
	}

	void ScanBlockFunc(){
		writeBuffer("y 2");
		checkFinish();
	}
	void RestPos(){
		writeBuffer("y 10");
		checkFinish();
		writeBuffer("y 1");
		checkFinish();
	}
	void ScanSea(){
		writeBuffer("y 5");
		checkFinish();
	}
	void ScanRail(){
		writeBuffer("y 6");
		checkFinish();
	}
	void StartUp(){
		writeBuffer("y 0");
		checkFinish();
		writeBuffer("y 1");
		checkFinish();
	}
	void OutWhole(){
		writeBuffer("e 170");
		writeBuffer("q 60");
	}
	void PickUpBlock(){
		writeBuffer("a 5 3000");
		checkFinish();
		writeBuffer("y 3");
		checkFinish();
		writeBuffer("a 5 800");
		checkFinish();
		CarryPos();

	}
	void CarryPos(){
		writeBuffer("y 10");
		checkFinish();
		writeBuffer("y 11");
		checkFinish();
	}
	void ScanDock(){
		writeBuffer("y 12");
		checkFinish();

	}
	void PlaceBlock(){
		writeBuffer("y 3");
		checkFinish();
		writeBuffer("a 5 2000");
		checkFinish();
		writeBuffer("y 10");
		checkFinish();
	}

	void writeBuffer(const char* data,int x =-1,int y =-1){
		std::string buffer;
		std::ostringstream ss;
		if(x!=-1)
			ss << " " << x;
		if(y!=-1)
			ss << " " << y;
		buffer.append(data);
		if(x!=-1 || y!=-1)
			buffer.append(ss.str());
		buffer.append(".");
		dataOutput = buffer;
		SendStuff(dataOutput);
		std::cout << dataOutput<<std::endl;

	}
	unsigned char* updateInput(){
		unsigned char* buff = new unsigned char[1024];
		RS232_PollComport(24,buff,1024);

		return buff;
	}
	void checkStart(){
		if(!debug){
			while(dataInput != 's'){
				RS232_PollComport(24,&dataInput,1);
				if(dataInput == (unsigned char)'s'){
					break;
				}
				sleep(1);
			}
			resetInput();
		}
		if(debug)
			std::cin.get();
	}
	void checkFinish(){
		if(!debug){
			while(dataInput != (unsigned char)'f'){
				RS232_PollComport(24,&dataInput,1);
				std::cout << "sleep " << dataInput <<std::endl;
				if(dataInput == (unsigned char)'f'){
					break;
				}
				sleep(1);
			}
		resetInput();
		}
		if(debug)
			std::cin.get();
	}

	void goUpRamp(){
		writeBuffer("g",(69 * 25.4),(8 * 25.4));
		checkFinish();
		writeBuffer("g",(69 * 25.4),(56 * 25.4));
		checkFinish();
		writeBuffer("g",0,(56 * 25.4));
		checkFinish();

	}

	std::string getdataOutput()const{return dataOutput;}
	unsigned char getfataInput()const{return dataInput;}


};


#endif /* BUFFER_H_ */
